package cn.qdu.controller;

import cn.qdu.model.Post;
import cn.qdu.model.User;
import cn.qdu.service.PostService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/post/*")
public class PostServlet extends HttpServlet {
    private PostService postService = new PostService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        if (pathInfo == null || pathInfo.equals("/")) {
            pathInfo = "/list";
        }

        switch (pathInfo) {
            case "/list":
                showPostList(request, response, currentUser);
                break;
            case "/create":
                showCreateForm(request, response);
                break;
            case "/edit":
                showEditForm(request, response, currentUser);
                break;
            case "/detail":
                showPostDetail(request, response, currentUser);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        if (pathInfo == null || pathInfo.equals("/")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        switch (pathInfo) {
            case "/create":
                createPost(request, response, currentUser);
                break;
            case "/update":
                updatePost(request, response, currentUser);
                break;
            case "/delete":
                deletePost(request, response, currentUser);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    private void showPostList(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        try {
            String type = request.getParameter("type");
            List<Post> posts = null;

            if (type == null || type.isEmpty()) {
                posts = postService.getPostsForUser(currentUser.getUserId(), currentUser.getUserId());
            } else if ("public".equals(type)) {
                posts = postService.getPublicPosts(currentUser.getUserId());
            } else if ("friends".equals(type)) {
                posts = postService.getFriendsPosts(currentUser.getUserId());
            } else if ("mine".equals(type)) {
                posts = postService.getUserPosts(currentUser.getUserId());
            }

            request.setAttribute("type", type);
            request.setAttribute("posts", posts);
            request.getRequestDispatcher("/views/post/post_list.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void showCreateForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/views/post/create_post.jsp").forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        try {
            int postId = Integer.parseInt(request.getParameter("id"));
            Post post = postService.getPostById(postId, currentUser.getUserId());

            if (post != null && post.getUserId().equals(currentUser.getUserId())) {
                request.setAttribute("post", post);
                request.getRequestDispatcher("/views/post/edit_post.jsp").forward(request, response);
            } else {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void showPostDetail(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        try {
            int postId = Integer.parseInt(request.getParameter("id"));
            Post post = postService.getPostById(postId, currentUser.getUserId());

            if (post != null) {
                request.setAttribute("post", post);
                request.getRequestDispatcher("/views/post/post_detail.jsp").forward(request, response);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void createPost(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        try {
            String content = request.getParameter("content");
            String visibility = request.getParameter("visibility");
            String location = request.getParameter("location");

            Post post = new Post();
            post.setUserId(currentUser.getUserId());
            post.setContent(content);
            post.setVisibility(visibility);
            post.setLocation(location);

            boolean success = postService.createPost(post);
            if (success) {
                response.sendRedirect(request.getContextPath() + "/post/list");
            } else {
                request.setAttribute("error", "发布日志失败");
                request.getRequestDispatcher("/views/post/create_post.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void updatePost(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        try {
            int postId = Integer.parseInt(request.getParameter("postId"));
            String content = request.getParameter("content");
            String visibility = request.getParameter("visibility");
            String location = request.getParameter("location");

            Post post = new Post();
            post.setPostId(postId);
            post.setUserId(currentUser.getUserId());
            post.setContent(content);
            post.setVisibility(visibility);
            post.setLocation(location);

            boolean success = postService.updatePost(post);
            if (success) {
                response.sendRedirect(request.getContextPath() + "/post/detail?id=" + postId);
            } else {
                request.setAttribute("error", "更新日志失败");
                request.getRequestDispatcher("/views/post/edit_post.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void deletePost(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        try {
            int postId = Integer.parseInt(request.getParameter("id"));

            boolean success = postService.deletePost(postId, currentUser.getUserId());
            if (success) {
                response.sendRedirect(request.getContextPath() + "/post/list");
            } else {
                request.setAttribute("error", "删除日志失败");
                request.getRequestDispatcher("/views/post/post_detail.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}